package com.yanguilai.rabbitmqtest;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@SpringBootApplication
public class RabbitmqTestApplication {

//    private final static String QUEUE_NAME = "hello";
    private final static String QUEUE_NAME = "task_queue";
    private final static boolean durable = true;
    private final static boolean autoAck = false;
    private final static int prefetchCount = 1;


    private static ConnectionFactory factory;

    static {
        factory = new ConnectionFactory();
        factory.setHost("c7formal");
    }

    public static void main(String[] args) {
        SpringApplication.run(RabbitmqTestApplication.class, args);

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
            channel.basicQos(prefetchCount);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

//            DeliverCallback callback = (tag, delivery) -> {
//                String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
//                System.out.println(" [x] Received '" + msg + "'");
//            };

            DeliverCallback callback = (tag, delivery) -> {
                String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println(" [x] Received '" + msg + "'");
                try {
                    doWork(msg);
                } finally {
                    System.out.println(" [x] Done");
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }
            };

            channel.basicConsume(QUEUE_NAME, autoAck, callback, tag -> {});
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }

    private static void doWork(String task) {
        for (char c : task.toCharArray()) {
            if (c == '.') {
                try {
                    System.out.println("sleeping...");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
